package com.thx.addressbook.action;

import com.thx.addressbook.model.AddressbookGroup;
import com.thx.addressbook.service.AddressbookGroupService;
import com.thx.common.struts2.CurdAction;
import com.thx.common.web.ActionResult;
import com.thx.log.LogUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.Date;

/**
 * 分组管理
 * 
 * @author conquerorpc
 *
 */
@ParentPackage(value = "gloab-package")
@Namespace(value = "/addressbook")
@Controller
@Scope("prototype")
@Action(value = "addressbookGroup",
    results = {@Result(name = "list", location = "/pages/addressbook/group/list.jsp"),
        @Result(name = "input", location = "/pages/addressbook/group/input.jsp"),
        @Result(name = "groupauthlist", location = "/pages/addressbook/group/list_auth.jsp"),
        @Result(name = "json", type = "json", params = {"root", "result"})},
    interceptorRefs = {@InterceptorRef(value = "topDtStack"),
        @InterceptorRef(value = "pageInterceptor", params = {"includeMethods", "list"}),
        @InterceptorRef(value = "pageInterceptor", params = {"includeMethods", "groupauthlist"}),})

public class AddressbookGroupAction extends CurdAction<AddressbookGroup> {

  private static final Logger logger = LoggerFactory.getLogger(AddressbookGroupAction.class);
  private static final long serialVersionUID = 1L;

  @Autowired
  private AddressbookGroupService service;

  private String ids;// 批量删除的id
  private String checkJson;

  private String pid;
  private String treeJson;
  private String searchGroupName;

  // 测试数据
  private Long personnelId = 1048L;
  private Long enterpriseId = 181L;

  protected void doList() {
    try {
      logger.info("<进入>分类分组信息查询list");
      logger.debug("<入参>searchGroupName:{}" + searchGroupName);
      logger.info("<入参>:查询父节点={}", pid);
      String[] pidArrays = StringUtils.split(pid, "_");
      Long acId = NumberUtils.toLong(pidArrays[1]);
      list = service.findByAgnameAndEnterpriseProperties(searchGroupName, enterpriseId, acId,
          personnelId);
      logger.debug("<出参>查询结果集{}：", list);
    } catch (Exception e) {
      logger.error("<错误>list查询异常{}", e);
    }
  }

  protected void doView() {
    try {
      logger.info("<进入>分类详情查询");
      logger.debug("<入参>查询参数id:{}", id);
      if (StringUtils.isNotBlank(id)) {
        entity = service.get(Long.parseLong(id));
      } else {
        logger.info("无法获取id");
      }
      logger.debug("<出参>查询结果{}：", entity);
    } catch (Exception e) {
      logger.error("<错误>分类详情查询异常{}", e);
    }
  }

  /**
   * 新增、修改显示页面.
   */
  public String input() {
    logger.debug("<进入>:分类修改/新增跳转方法");
    logger.info("<入参>:查询父节点={}", pid);
    logger.info("<入参>:id={}", id);
    try {
      if (StringUtils.isNotBlank(id)) {
        entity = service.get(Long.parseLong(id));
      }
      logger.debug("<出参>查询结果{}：", entity);
    } catch (Exception e) {
      logger.error("<错误>:查询异常");
    }
    return "input";
  }

  /**
   * 新增修改方法.
   */
  public void doSave() {
    try {
      if (StringUtils.isBlank(id)) {
        logger.debug("<进入>:分类管理新增方法");
        logger.info("<入参>:新增数据={}", entity);
        logger.info("<入参>:查询父节点={}", pid);
        String[] pidArrays = StringUtils.split(pid, "_");
        AddressbookGroup entityd = new AddressbookGroup();
        entityd.setEnterpriseId(enterpriseId);
        entityd.setAgName(entity.getAgName());
        entityd.setAcId(NumberUtils.toLong(pidArrays[1]));
        entityd.setEnterpriseId(enterpriseId);
        entityd.setPersonnelId(personnelId);
        entityd.setCreateTime(new Date());
        service.save(entityd);
        setResult(SUCCESS, "新增成功！");
        LogUtil.log("分类管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "新增信息");
      } else {
        logger.debug("<进入>:分类管理修改方法");
        logger.info("<入参>:修改分类id={}", entity);
        AddressbookGroup entityd = service.get(Long.parseLong(id));
        entityd.setAgName(entity.getAgName());
        entityd.setUpdateTime(new Date());
        service.update(entityd);
        setResult(SUCCESS, "修改成功！");
        LogUtil.log("分类管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "修改信息");
      }
    } catch (Exception e) {
      if (StringUtils.isNotBlank(id)) {
        LogUtil.log("分类管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_FAIL, "修改信息");
        logger.error("<错误>:修改异常{}", e);
      } else {
        LogUtil.log("分类管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_FAIL, "新增信息");
        logger.error("<错误>:新增异常{}", e);
      }
    }
  }

  protected void doDelete() {
    logger.debug("<进入>:删除分类信息方法");
    try {
      if (StringUtils.isNotBlank(id)) {
        logger.info("<入参>:分类信息数据pid={}", pid);
        logger.info("<入参>:分类信息数据id={}", id);
        logger.info("<入参>:分类信息数据id={}", entity);
        service.delete(NumberUtils.toLong(id));
        setResult(ActionResult.SUCCESS, "删除成功！");
        LogUtil.log("分类信息管理", LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS, "删除分类信息");
      } else {
        setResult(ActionResult.FAIL, "服务器异常！");
      }
    } catch (Exception e) {
      logger.error("<错误>:删除异常{}", e);
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  /**
   * 批量删除信息.
   */
  protected void doDelMulti() {
    logger.debug("<进入>:批量分类信息方法");
    try {
      if (ids != null && ids.split(",").length > 0) {
        logger.info("<入参>:批量删除分类信息id={}", ids);
        for (String del : ids.split(",")) {
          service.delete(NumberUtils.toLong(del));
        }
        setResult(ActionResult.SUCCESS, "批量删除成功！");
        LogUtil.log("分类数据管理", LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS, "批量删除信息");
      } else {
        setResult(ActionResult.FAIL, "服务器异常！");
      }
    } catch (Exception e) {
      logger.error("<错误>:批量删除异常{}", e);
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  /**
   * 校验分组名称是否存在.
   */
  public void checkName() {
    // logger.debug("<进入>:分类信息验证方法");
    // try {
    // logger.info("<入参>:分类信息名称={}", entity.getLabelCn());
    // PhoneTariff f =
    // surveyClassService.findBySmsoperators(entity.getLabelCn());
    // logger.debug("<出参>:分类信息{}", f);
    // if (f == null) {
    // checkJson = JSONObject.toJSONString(true);
    // } else {
    // if (f.getId().toString().equals(id)) {
    // checkJson = JSONObject.toJSONString(true);
    // } else {
    //
    // checkJson = JSONObject.toJSONString(false);
    // }
    // }
    // logger.info("<出参>:资费信息checkJson={}", checkJson);
    // writeJson(checkJson);
    // } catch (Exception e) {
    // logger.error("<错误>:验证异常{}",e);
    // }
  }

  /**
   * 根据分类查询分组树节点.
   */
  public void listtree() {
    try {
      logger.info("<进入>分类分组信息查询list");
      logger.info("<入参>:查询父节点={}", pid);
      String[] pidArrays = StringUtils.split(pid, "_");
      Long acId = NumberUtils.toLong(pidArrays[1]);
      list = service.findAllByAgnameAndEnterpriseProperties(searchGroupName, enterpriseId, acId,
          personnelId);
      treeJson = com.alibaba.fastjson.JSON.toJSONString(list);
      writeJson(treeJson);
      setResult(SUCCESS, "查询成功！");
      logger.debug("<出参>查询结果集{}：", list);
    } catch (Exception e) {
      logger.error("<错误>list查询异常{}", e);
    }
  }

  /**
   * 分组授权列表页面.
   */
  public String groupauthlist() {
    try {
      logger.debug("<进入>分类列表信息查询list");
      String[] pidArrays = StringUtils.split(pid, "_");
      Long acId = NumberUtils.toLong(pidArrays[1]);
      list = service.findByAgnameAndEnterpriseProperties(searchGroupName, enterpriseId, acId,
          personnelId);
      logger.debug("<出参>查询结果集{}：", list);
    } catch (Exception e) {
      logger.error("<错误>enterpriseCategoryList查询异常{}", e);
    }
    return "groupauthlist";
  }

  public String getIds() {
    return ids;
  }

  public void setIds(String ids) {
    this.ids = ids;
  }

  public String getCheckJson() {
    return checkJson;
  }

  public void setCheckJson(String checkJson) {
    this.checkJson = checkJson;
  }

  public String getPid() {
    return pid;
  }

  public void setPid(String pid) {
    this.pid = pid;
  }

  public String getSearchGroupName() {
    return searchGroupName;
  }

  public void setSearchGroupName(String searchGroupName) {
    this.searchGroupName = searchGroupName;
  }

  public String getTreeJson() {
    return treeJson;
  }

  public void setTreeJson(String treeJson) {
    this.treeJson = treeJson;
  }

}
